package com.gxxy.spring.kp03_aop.cls01_proxy.s2_dynamic.k02_inherit;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.InvocationHandler;

// CGLib: Code Generation Library
// javassist: 代码生生的库

// 可以把这个对象想象成一个拦截器
public class TransactionInvocationHandler implements InvocationHandler {

	private Object service;
	private TransactionManager txMgr;

	public TransactionInvocationHandler(Object service,
			TransactionManager txMgr) {
		this.service = service;
		this.txMgr = txMgr;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		//System.out.println("~~~~~:\n" + method.getName());
		//System.out.println("args:" + args);
		// public abstract void 
		//com.gxxy.spring.kp03_aop.cls01_proxy.s2_dynamic.k01_interface.
		//IStudentService.save(..) throws java.lang.Exception

		Object object = null;
		try {
			txMgr.begin();
			object = method.invoke(service, args);
			txMgr.commit();
		} catch (Exception e) {
			txMgr.rollback();
		} finally {
			txMgr.finished();
		}

		return object;
	}

}
